import tkinter as tk
from tkinter import ttk, messagebox
import joblib
import pandas as pd


def gui_load_model():
    try:
        # 加载模型和标准化器
        loaded_model = joblib.load('logistic_regression_model.pkl')
        transfer = joblib.load('scaler.pkl')
    except FileNotFoundError:
        messagebox.showerror("错误", "未找到模型文件，请先运行'生成模型'选项")
        return

    # 示例测试数据（特征顺序与训练时一致）
    test_samples = pd.DataFrame({
        'Clump Thickness': [2, 5, 8],
        'Uniformity of Cell Size': [1, 3, 6],
        'Uniformity of Cell Shape': [1, 2, 5],
        'Marginal Adhesion': [1, 2, 4],
        'Single Epithelial Cell Size': [2, 3, 4],
        'Bare Nuclei': [1, 2, 7],
        'Bland Chromatin': [2, 4, 6],
        'Normal Nucleoli': [1, 2, 3],
        'Mitoses': [1, 1, 2]
    })

    # 标准化测试数据
    test_samples_scaled = transfer.transform(test_samples)

    # 模型预测
    test_pred = loaded_model.predict(test_samples_scaled)

    # 转换为中文标签
    class_mapping = {2: '良性', 4: '恶性'}
    test_pred_chinese = [class_mapping[label] for label in test_pred]

    # 创建新窗口展示结果
    result_window = tk.Toplevel()
    result_window.title("预测结果")

    # 添加描述文本
    desc_label = tk.Label(result_window, text="以下为模型对测试样本的预测结果：", font=("Arial", 12))
    desc_label.pack(pady=10)

    # 创建表格
    columns = list(test_samples.columns) + ['预测类别']
    tree = ttk.Treeview(result_window, columns=columns, show='headings', height=5)
    tree.pack(padx=10, pady=10, fill='both', expand=True)

    # 设置列标题
    for col in columns:
        tree.heading(col, text=col)
        tree.column(col, width=100, anchor='center')

    # 插入数据行
    for i in range(len(test_samples)):
        row_data = list(test_samples.iloc[i]) + [test_pred_chinese[i]]
        tree.insert('', 'end', values=row_data)

    # 添加关闭按钮
    close_button = tk.Button(result_window, text="关闭", command=result_window.destroy)
    close_button.pack(pady=5)


# 示例主窗口调用函数
def main():
    root = tk.Tk()
    root.title("乳腺癌分类模型系统")
    root.geometry("400x300")

    # 按钮：加载模型并显示结果
    load_button = tk.Button(root, text="加载模型并预测", command=gui_load_model, font=("Arial", 14), width=20)
    load_button.pack(pady=100)

    root.mainloop()


if __name__ == "__main__":
    main()
